import axios, { type AxiosInstance, type AxiosRequestConfig, type AxiosResponse } from "axios";
import { useAppStore } from "@/stores";
import { showDialog } from "vant";

export interface HttpResponse<T = unknown> {
  status: number;
  msg: string;
  code: number;
  data: T;
}

// 创建 axios 实例
const http: AxiosInstance = axios.create({
  baseURL: "", // 统一设置 baseURL
  timeout: 10000, // 请求超时时间
});

// 请求拦截器
http.interceptors.request.use(
  (config: any) => {
    const urlParams = new URLSearchParams(window.location.search);
    const urlOkey = urlParams.get("okey");
    if (!urlOkey) {
      showDialog({ message: "钥匙不见了，请呼叫管理员投放" });
      return Promise.reject(new Error("Missing okey – request aborted"));
    }

    config.params = { ...config.params, okey: urlOkey };
    if (config.method?.toLowerCase() === "post") {
      config.data = { ...config.data, okey: urlOkey };
    }
    return config;
  },
  (error) => Promise.reject(error)
);

// 响应拦截器
http.interceptors.response.use(
  (response: AxiosResponse<HttpResponse>) => {
    const res = response.data;

    if (res.code !== 200) {
      return Promise.reject(new Error(res.msg || "Error"));
    }
    return response;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 封装通用请求方法
const request = <T = unknown>(config: AxiosRequestConfig): Promise<HttpResponse<T>> => {
  return http(config).then((res) => res.data);
};

export default request;
